using System;
using System.Linq;
using System.Web.Mvc;
using Omu.Awesome.Mvc;
using Uber.Core;
using Uber.Core.Model;
using Uber.Core.Repository;

namespace Uber.WebUI.Controllers
{
    [Authorize]
    public class NotificationsController : Controller
    {
        private readonly IRepo<Notification> r;
        private const int ps = 5;

        public NotificationsController(IRepo<Notification> r)
        {
            this.r = r;
        }
        public ActionResult Index()
        {
            return View(Fa.Account.Get(Gl.UserId()));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ReadAll()
        {
            Fa.Notification.ReadAll(Gl.UserId());
            return RedirectToAction("index");
        }
        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteAll()
        {
            Fa.Notification.DeleteAll(Gl.UserId());
            return RedirectToAction("index");
        }

        public ActionResult Rows(int p)
        {
            var uid = Gl.UserId();
            var data = r.Where(o => o.AccountId == uid).OrderByDescending(o => o.Date);
            return Json(new { c = this.RenderView("Rows", data.Pag(p, ps)), m = data.Count() > ps * p });
        }

        public ActionResult Link()
        {
            var uid = Gl.UserId();
            try
            {
                var unread = r.Where(o => o.AccountId == uid && o.IsRead == false).Count();
                var s = (unread == 0) ? "notifications" : "notifications (" + unread + ")";
                return Content("<a href='" + Url.Action("Index") + "'>" + s + "</a>");
            }
            catch(Exception ex)
            {
                ex.Raize();
            }
            return Content("");
        }

        [HttpPost]
        public ActionResult SaveMailSettings(bool mailOnAnswer, bool mailOnComment)
        {
            Fa.Account.SaveMailSettings(mailOnAnswer, mailOnComment, Gl.UserId());
            return Content("o");
        }
    }
}